package org.itboys.ace.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.itboys.ace.dto.ZTreeDto;
import org.itboys.admin.entity.AdminMenu;
import org.itboys.admin.entity.AdminRole;

import org.itboys.admin.service.*;
import org.itboys.admin.tools.AdminPermissionCheck;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.collection.CommonCollectionUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.AceJsonPageUtils;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.AceUtils;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/***
 * 用户角色管理
 * 
 * @author cxj123
 *
 */
@RestController
@RequestMapping("/ace/admin/role")
public class AceAdminRoleController extends BaseController {
	@Autowired
	private AdminRoleService adminRoleService;
	@Autowired
	private ResourceHolder resourceHolder;
	@Autowired
	private AdminModuleService adminModuleService;
	@Autowired
	private AdminPermissionService adminPermissionService;
	@Autowired
	private AdminMenuService adminMenuService;
	@Autowired
	private AdminRolePermissionRelService adminRolePermissionRelService;

	
	
	/**
	 * 点击角色管理跳转页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/role-list")
	public ModelAndView listvm(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return new ModelAndView("/ace/admin/role-list");
	}

	/***
	 * 分页获取用户角色相关信息
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	@AdminPermissionCheck("adminRole:list")
	public void list(HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		if (null != param.get("name")) {
			param.put("name", AceUtils.getPattern(param.get("name")));
		}
		Page<AdminRole> page = adminRoleService.pageQuery(param, request);
		AceJsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}

	/***
	 * 新增角色
	 * 
	 * @param adminRole
	 * @param response
	 */
	@RequestMapping("/saveRole")
	public void add(@ModelAttribute AdminRole adminRole,HttpServletRequest request,
			HttpServletResponse response) {
		try{
			if(adminRole==null||adminRole.getId()==0l){
				adminRoleService.insert(adminRole);
			}else{
				adminRoleService.update(adminRole);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			logger.error("AdminRole save error", e);
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	/**
	 * 删除指定记录
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	public void delete(@PathVariable("id") Long id, HttpServletResponse response){
		try {
			adminRoleService.delete(id);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("AdminRole delete error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	/**
	 * 菜单树形结构数据
	 * @param id
	 * @param response
	 */
	@RequestMapping("/getMenuPermission/{id}")
	public void getMenuPermission(@PathVariable("id") Long id,HttpServletResponse response){
		Map<String, Object> param = Maps.newHashMapWithExpectedSize(0);
		List<AdminMenu> menuList = adminMenuService.list(param);
		List<Long> menuIds = adminMenuService.getAdminMenuByRoleIds(id);
		List<AdminMenu> roots = adminMenuService.getRootsMenusIgnorePermission(menuList);
		List<ZTreeDto> tree = Lists.newArrayListWithCapacity(roots.size());
		List<ZTreeDto> treeChild = Lists.newArrayListWithCapacity(menuList.size());
		for(AdminMenu menu:roots){
			ZTreeDto menuTree = new ZTreeDto();
			menuTree.setId(menu.getId());
			menuTree.setpId(menu.getParentId());
			menuTree.setName(menu.getMenuName());
			menuTree.setOpen(true);
			if(menuIds.contains(menu.getId())){
				menuTree.setChecked(true);
			}
			tree.add(menuTree);
		}
		treeChild.addAll(tree);
		for(ZTreeDto uitree:tree){
			for(AdminMenu menu:menuList){
				if(menu.getParentId().equals(uitree.getId())){
					ZTreeDto menuTree = new ZTreeDto();
					menuTree.setId(menu.getId());
					menuTree.setName(menu.getMenuName());
					menuTree.setpId(menu.getParentId());
					menuTree.setOpen(true);
					if(menuIds.contains(menu.getId())){
						menuTree.setChecked(true);
					}
					treeChild.add(menuTree);
				}
			}
		}
		AjaxUtils.renderJson(response, treeChild);
	}
	/***
	 * 保存角色~菜单关联表信息
	 * @param response
	 * @param request
	 */
	@RequestMapping("/relPermissionAndMenu")
	public void relPermissionAndMenu(HttpServletResponse response,HttpServletRequest request){
		try {
			String str = request.getParameter("permissionIds");
			Long roleId = Long.valueOf(request.getParameter("roleId"));	
			String types = request.getParameter("types");
			List<Long> permissionIds = CommonCollectionUtils.splictToLongList(str, ",");
			if(types.equals("access")){
			}else{
				adminRoleService.insertRoleMenu(roleId,permissionIds,types);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	/***
	 * 根据角色id查询角色信息
	 * @param id
	 * @param response
	 */
	@RequestMapping("/getRoleById/{id}")
	public void getOrg(@PathVariable("id") Long id, HttpServletResponse response) {
		AjaxUtils.renderJson(response, adminRoleService.getById(id));
	}
	
}
